import { betterAuth } from 'better-auth'
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { nuxtdb } from './db/database' // your drizzle instance
import { username, openAPI, admin, organization, genericOAuth } from 'better-auth/plugins'

const config = useRuntimeConfig()

export const auth = betterAuth({
  csrf: false,
  database: drizzleAdapter(nuxtdb, {
    provider: 'pg' // or "mysql", "sqlite"
  }),
  emailAndPassword: {
    enabled: true
  },
  plugins: [
    username(), openAPI(), admin(), organization(), genericOAuth({
      config: [
        {
          providerId: 'li-gitee',
          clientId: 'f85895469d8aa071204e7789477ab9142ba0064541b69dc45b959ebacb18579f',
          clientSecret: '5ea637f6a579a377d0d5c2544f45146d89b730e195dea15c5b73b619e13204d2',
          authorizationUrl: 'https://gitee.com/oauth/authorize',
          tokenUrl: 'https://gitee.com/oauth/token',
          redirectURI: 'http://localhost:3500/api/auth/oauth2/callback/li-gitee',
          scopes: ['user_info'],
          responseType: 'code',
          pkce: true,
          getUserInfo: async (tokens) => {
            const response = await fetch('https://gitee.com/api/v5/user', {
              headers: {
                'Authorization': `Bearer ${tokens.accessToken}`,
                'X-Custom-Header': 'value'
              }
            })
            const emailresponse = await fetch('https://gitee.com/api/v5/emails', {
              headers: {
                'Authorization': `Bearer ${tokens.accessToken}`,
                'X-Custom-Header': 'value'
              }
            })

            const userData = await response.json()
            const emailData = await emailresponse.json()
            console.log('userData', userData)
            console.log('emailData', emailData)
            return {
              id: userData.id.toString(),
              email: emailData[0].email || '',
              name: userData.name || '',
              image: userData.avatar_url,
              emailVerified: !!(emailData[0].email)
            }
          }
        }
      ]
    })
  ],
  trustedOrigins: [config.BETTER_AUTH_URL || '', config.BETTER_AUTH_URL || ''],
  advanced: {
    crossSubDomainCookies: {
      enabled: true,
      domain: config.DOMAIN
    },
    defaultCookieAttributes: {
      secure: true,
      httpOnly: true,
      sameSite: 'none',
      partitioned: true
    }
  }
})

// npx @better-auth/cli@latest info --config ./server/lib/auth.ts
// npx @better-auth/cli@latest generate --config ./server/lib/auth.ts --output ./app/utils/db/auth-schema.ts --yes
